/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdmEmployeePanel.java
 *
 * Created on 28-11-2011, 11:06:48
 */
package GUILag;

import ControllerLag.EmployeeCTR;
import ModelLag.Employee;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * GUI - Panel til styring af CRUD employee funktionaliteter.
 * @author DM75 Gruppe 3
 * @version 2011-12-22
 */
public class AdmEmployeePanel extends javax.swing.JPanel {
    
    private EmployeeCTR employeeCtr;
    private MyTableCellRenderer cellRender;

    /** Creates new form AdmEmployeePanel */
    public AdmEmployeePanel() {
        initComponents();
        
        employeeCtr = new EmployeeCTR();
        cellRender = new MyTableCellRenderer();
        // Indsætter data i tabellen i GUI.
        updateEmployeeTable();
    }
    
    /**
     * Henter den model som bruges i netbeans GUI, så man kan sætte properties ved
     * at højreklikke på tabellen i IDE. Man slipper derved for at skrive det i koden
     * eller at skulle lave sin egen tablemodel.
     * @return Tablemodel som bruges.
     */
    private DefaultTableModel getModel()
    {
        return (DefaultTableModel) employeeTable.getModel();
    }
   
    /**
     * Bruges til at tilføje en række til modellen/tabellen. Derefter tilføjer den
     * det data som er med som parameter. Når der tilføjes noget til modellen, så
     * opdateres tabellen automatisk. 
     * @param cprNo CprNo på employee.
     * @param fName Fornavn på employee.
     * @param lName Efternavn på employee.
     * @param address Adresse på employee.
     * @param zipCode PostNr på employee.
     * @param city By på employee.
     * @param email Email på employee.
     * @param phoneNo TelefonNr på employee.
     * @param sort Bestemmer om modellen skal sorteres i 0. kolonne.
     */
    private void addRowAndData(String cprNo, String fName, String lName, String address, String zipCode, String city, String email, String phoneNo,boolean active, boolean sort)
    {
        Boolean isActive = employeeCtr.findEmployee(cprNo).isActive();
        Object[] data = {cprNo, fName, lName, address, zipCode, city, email, phoneNo,isActive};

        getModel().addRow(data);
        
    
        if(sort)
        {
            sortTable();
        }
    
    }
    
    /**
     * Sortering af tabellen (den man ser) efter 0.kolonne. Sortere IKKE modellen.
     */
    private void sortTable()
    {
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(getModel());
        List <RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
        sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
        sorter.setSortKeys(sortKeys);
        employeeTable.setRowSorter(sorter);
    }
    
    
    /**
     * Henter alle employees og gemmer dem i en midlertidig ArrayList. I denne ArrayList
     * tages hvert element og så hentes der CprNo, Fornavn, Efternavn, Adresse, PostNr, By, Email og TelefonNr .
     * Derefter tilføjes disse til modellen og dermed til tabellen.
     */
    private void updateEmployeeTable()
    {
        ArrayList<Employee> employees = employeeCtr.getAllEmployees();

        String cprNo = "";
        String fName = "";
        String lName = "";
        String address = "";
        String zipCode = "";
        String city = "";
        String email = "";
        String phoneNo = "";
        boolean active;
        
        for(Employee employeeObj : employees)
        {   
            cprNo = employeeObj.getCprNo();
            fName = employeeObj.getfName();
            lName = employeeObj.getlName();
            address = employeeObj.getAddress();
            zipCode = employeeObj.getZipCode();
            city = employeeObj.getCity();
            email = employeeObj.getEmail();
            phoneNo = employeeObj.getPhoneNo();
            active = employeeObj.isActive();
            
            // Sortering foregår i databasen efter CprNo, fName, lName, addres, city, email og phoneNo. derfor false.
            addRowAndData(cprNo, fName, lName, address, zipCode, city, email, phoneNo,  active, false);

        }
        
    }
    
    /**
     * Sletter en række alt efter rækkenr i tabellen. Den konvertere først rækkenr
     * i tabellen til tilsvarende rækkenr i modellen da disse kan være forskellige
     * pga. at sorteringen foregår i tabellen og ikke i modellen. Derefter slettes
     * rækken i modellen og dermed i tabellen.
     * @param rowNo Rækkenr i tabellen som skal slettes. 
     */
    private void removeRow(int rowNo)
    {
        rowNo = employeeTable.convertRowIndexToModel(rowNo);
        getModel().removeRow(rowNo);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        createEmployeeButton = new javax.swing.JButton();
        updateEmployeeButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        employeeTable = new javax.swing.JTable();

        createEmployeeButton.setText("Opret medarbejder");
        createEmployeeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createEmployeeButtonActionPerformed(evt);
            }
        });

        updateEmployeeButton.setText("Opdater medarbejder");
        updateEmployeeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateEmployeeButtonActionPerformed(evt);
            }
        });

        employeeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cpr nr.", "Fornavn", "Efternavn", "Adresse", "Post nr.", "By", "Email", "Telefon nr.", "Active"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        employeeTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        employeeTable.getTableHeader().setReorderingAllowed(false);
        employeeTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                employeeTableMouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(employeeTable);
        employeeTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        employeeTable.getColumnModel().getColumn(8).setPreferredWidth(50);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(updateEmployeeButton)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(createEmployeeButton)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 613, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(58, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(createEmployeeButton)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(updateEmployeeButton)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * Her oprettes en employee ved hjælp af JOptionPane hvor der er 7 textfields,
     * hvor de forskellige data bliver indsat.
     * rc = 1. Oprettelsen gik godt i databasen.
     * rc -1. Fejl ved oprettelse i databasen. 
     */
    private void createEmployeeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createEmployeeButtonActionPerformed
        JTextField cprNoField = new JTextField();
        JTextField fNameField = new JTextField();
        JTextField lNameField = new JTextField();
        JTextField addressField = new JTextField();
        JTextField zipCodeField = new JTextField();
        JTextField emailField = new JTextField();
        JTextField phoneNoField = new JTextField();
        int rc =0;
        
        // Strings og JTexFields som skal vises i JOptionpane.
        Object[] message = new Object[] {"Cpr nr.:", cprNoField, "Fornavn:", fNameField, "Efternavn:", lNameField, "Adresse:", addressField, "Post nr.:", zipCodeField, "Email:", emailField, "Telefon nr.:", phoneNoField};
        
        
        // En anden form for JOptionpane.
        //int input = JOptionPane.showConfirmDialog(this, message, "Opret ny medarbejder", JOptionPane.OK_CANCEL_OPTION); HER er OK Knappen i fokus fra start!
        
        //Knapper på JOptionpane, som der har knapperne "OK" og "Annuller".
        Object[] options = {"OK", "Annuller"};
        
        int input = JOptionPane.showOptionDialog(this, message, "Opret ny medarbejder", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");
        
        if(input == JOptionPane.OK_OPTION)
        {
            if (cprNoField.getText().length() > 0 && cprNoField.getText().length() == 11)
            {
                try
                {
                    if(cprNoField.getText().substring(6,7).equals("-"))
                    {

 
                try
                    {   
                        rc = employeeCtr.createEmployee( cprNoField.getText(), fNameField.getText(), lNameField.getText(), addressField.getText(), zipCodeField.getText().toString().trim(), emailField.getText(), phoneNoField.getText(), true);
                    }
                    catch(SQLException e)
                    {
                    
                    }
                
                //rc = return code
                    if(rc == 1)
                    {
                        Employee empl = employeeCtr.findEmployee(cprNoField.getText());
                    
                        addRowAndData(cprNoField.getText(), fNameField.getText(), lNameField.getText(), addressField.getText(), zipCodeField.getText(), empl.getCity(), emailField.getText(), phoneNoField.getText(),empl.isActive(), true);
                        JOptionPane.showMessageDialog(this, "Medarbejder "+ fNameField.getText()+ " " + lNameField.getText() + " er nu oprettet", "Oprettelse lykkedes", JOptionPane.INFORMATION_MESSAGE);
                    
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(this, "Der er opstået en fejl. Medarbejder" + fNameField.getText() + "" + lNameField.getText() + " eksisterer muligvis i forvejen.", "oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
                    }
                    }
                    else
                        {
                            JOptionPane.showMessageDialog(this, "bindestreg skal indtastes det rigtige sted: format xxxxxx-xxxx", "oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
                        }
                }
                catch(Exception e)
                {
                    JOptionPane.showMessageDialog(this, "bindestreg skal indtastes det rigtige sted: format xxxxxx-xxxx", "oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
                }
                
            }
            else
            {
                JOptionPane.showMessageDialog(this, "Der er opstået en fejl.", "oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
            }
            
        }
        
    }//GEN-LAST:event_createEmployeeButtonActionPerformed
    
    // employee opdateres ved hjælp af den markerede række i tabellen hvor Cpr nummet bruges til opdatering.
    // rc = 1. Opdatering gik godt i databasen.
    // rc = -1. Opdatering mislykkedes.
    private void updateEmployeeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateEmployeeButtonActionPerformed
        int rowSelected = employeeTable.getSelectedRow();
        int rc = 0;
        if(rowSelected == -1)
        {
            JOptionPane.showMessageDialog(this ,"vælg medarbejderen som skal opdateres.", "Vælg medarbejderen", JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            
            String cprNo = (String) employeeTable.getValueAt(rowSelected, 0);
            String fName = (String) employeeTable.getValueAt(rowSelected, 1);
            String lName = (String) employeeTable.getValueAt(rowSelected, 2);
            String address = (String) employeeTable.getValueAt(rowSelected, 3);
            String zipCode = (String) employeeTable.getValueAt(rowSelected, 4);
            String city = (String) employeeTable.getValueAt(rowSelected, 5);
            String email = (String) employeeTable.getValueAt(rowSelected, 6);
            String phoneNo = (String) employeeTable.getValueAt(rowSelected, 7);
            boolean active = (Boolean) employeeTable.getValueAt(rowSelected, 8);
            JTextField fNameField = new JTextField(fName);
            JTextField lNameField = new JTextField(lName);
            JTextField addressField = new JTextField(address);
            JTextField zipCodeField = new JTextField(zipCode);
            JTextField cityField = new JTextField(city);
            JTextField emailField = new JTextField(email);
            JTextField phoneNoField = new JTextField(phoneNo);
            
            Object[] message = new Object[] {"Cpr nr.: " + cprNo, "Fornavn:", fNameField, "Efternavn:", lNameField, "Adresse:", addressField, "Post nr.:", zipCodeField,"By:", cityField,"Email:", emailField, "Telefon nr.:", phoneNoField};       
            Object[] options = { "Opdater", "Annuller"};
            
            //Bruges for at få fokus i det første textfield i JOptionpanet.
            int input = JOptionPane.showOptionDialog(this, message, "Opdatering af medarbejder", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");
            
            if(input == JOptionPane.OK_OPTION)
            {
                if(fNameField.getText().length() > 0)
                {
                    try{
                    rc = employeeCtr.updateEmployee(cprNo, fNameField.getText(), lNameField.getText(), addressField.getText(), zipCodeField.getText(), emailField.getText(), phoneNoField.getText(),active);
                    }catch(SQLException e){
                        
                    }


                    if(rc == 1)
                    {   
                        employeeTable.setValueAt(cprNo, rowSelected, 0);
                        employeeTable.setValueAt(fNameField.getText(), rowSelected, 1);
                        employeeTable.setValueAt(lNameField.getText(), rowSelected, 2);
                        employeeTable.setValueAt(addressField.getText(), rowSelected, 3);
                        employeeTable.setValueAt(zipCodeField.getText(), rowSelected, 4);
                        employeeTable.setValueAt(cityField.getText(), rowSelected, 5);
                        employeeTable.setValueAt(emailField.getText(), rowSelected, 6);
                        employeeTable.setValueAt(phoneNoField.getText(), rowSelected, 7);
                        JOptionPane.showMessageDialog(this, "Medarbejderen er opdateret.", "Opdatering lykkedes", JOptionPane.INFORMATION_MESSAGE);  
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(this, "En fejl er opstået", "Opdatering mislykkedes", JOptionPane.ERROR_MESSAGE);
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Der skal indtastet de rigtige data.", "Oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
                }
            }
        
        }
    
    }//GEN-LAST:event_updateEmployeeButtonActionPerformed
    
    // employee slettes ved hjælp af den markerede række i tabellen hvor cprNo bruges til sletning.
    // rc = 1. Sletning gik godt i databasen.
    // rc = -1. Sletning mislykkedes.
private void employeeTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_employeeTableMouseReleased
    try{
        if(employeeTable.getSelectedColumn() == 8)
        {
        int rc = employeeCtr.toggleActive(employeeTable.getValueAt(employeeTable.getSelectedRow(), 0).toString());    
        }
    }catch(Exception e){
        
    }
}//GEN-LAST:event_employeeTableMouseReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createEmployeeButton;
    private javax.swing.JTable employeeTable;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton updateEmployeeButton;
    // End of variables declaration//GEN-END:variables
}
